package com.geoai.featstatusbar.flightcheck.custom

import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import android.view.ViewGroup
import android.graphics.drawable.ColorDrawable
import android.widget.*
import androidx.recyclerview.widget.RecyclerView
import com.geoai.featstatusbar.databinding.LayoutCommonItemSpinnerBinding
import com.geoai.featstatusbar.databinding.LayoutCommonSpinnerPopWindowBinding

/**
 * @author : XPY on 2024/3/4 17:10
 * @description:
 */
class SpinnerPopWindow @JvmOverloads constructor(
    context: Context?,
    list: Array<String>,
    w: Int = ViewGroup.LayoutParams.WRAP_CONTENT
) : PopupWindow(context) {
    init {
        val viewBinding = LayoutCommonSpinnerPopWindowBinding.inflate(LayoutInflater.from(context))
        contentView = viewBinding.root

        width = w
        height = ViewGroup.LayoutParams.WRAP_CONTENT
        isFocusable = true
        isOutsideTouchable = true

        setBackgroundDrawable(ColorDrawable(Color.parseColor("#80000000")))

        viewBinding.rvSpPop.adapter = SpPopListAdapter(list)
    }

    inner class SpPopListAdapter(
        private var list: Array<String>
    ) :
        RecyclerView.Adapter<ViewHolder>() {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            return ViewHolder(LayoutCommonItemSpinnerBinding.inflate(LayoutInflater.from(parent.context)))
        }

        override fun getItemCount(): Int {
            return list.size
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            holder.bind(list[position], position)
        }
    }

    inner class ViewHolder(private val itemViewBinding: LayoutCommonItemSpinnerBinding) :
        RecyclerView.ViewHolder(itemViewBinding.root) {
        fun bind(
            value: String,
            position: Int
        ) {
            itemViewBinding.tvSpPopValue.text = value
            itemViewBinding.root.setOnClickListener {
                onSpinnerItemListener?.onValue(value, position)

                dismiss()
            }
        }
    }

    private var onSpinnerItemListener: OnSpinnerItemListener? = null

    interface OnSpinnerItemListener {
        fun onValue(value: String, position: Int)
    }

    fun setOnItemListener(clickListener: OnSpinnerItemListener) {
        onSpinnerItemListener = clickListener
    }
}